<template>
  <el-card style="width: 100%">
    <!-- 标题 -->
    <template #header>
      <div class="flex-between">
        <span>现场挂号</span>
      </div>
    </template>

    <!-- 挂号表单 -->
    <el-form
        :model="form"
        ref="registerForm"
        :rules="rules"
        label-width="120px"
        class="mt-4"
    >
      <!-- 病历号 -->
      <el-form-item label="病历号">
        <el-input v-model="form.casenumber" disabled />
      </el-form-item>

      <!-- 姓名 -->
      <el-form-item label="姓名" prop="realname">
        <el-input v-model="form.realname" placeholder="请输入姓名" />
      </el-form-item>

      <!-- 性别 -->
      <el-form-item label="性别" prop="gender">
        <el-select v-model="form.gender" placeholder="请选择">
          <el-option label="男" :value="71" />
          <el-option label="女" :value="72" />
        </el-select>
      </el-form-item>

      <!-- 身份证号 -->
      <el-form-item label="身份证号" prop="idnumber">
        <el-input v-model="form.idnumber" placeholder="请输入身份证号" />
      </el-form-item>

      <!-- 年龄 + 年龄类型 -->
      <el-row :gutter="20">
        <el-col :span="12">
          <el-form-item label="年龄">
            <el-input v-model="form.age" disabled />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="年龄类型" prop="agetype">
            <el-select v-model="form.agetype" placeholder="请选择">
              <el-option label="天" value="天" />
              <el-option label="月" value="月" />
              <el-option label="岁" value="岁" />
            </el-select>
          </el-form-item>
        </el-col>
      </el-row>

      <!-- 出生日期 -->
      <el-form-item label="出生日期">
        <el-date-picker
            v-model="form.birthdate"
            type="date"
            placeholder="请选择日期"
        />
      </el-form-item>

      <!-- 家庭住址 -->
      <el-form-item label="家庭住址">
        <el-input v-model="form.homeaddress" placeholder="选填" />
      </el-form-item>

      <!-- 挂号级别 -->
      <el-form-item label="挂号级别" prop="registleid">
        <el-select v-model="form.registleid" placeholder="请选择挂号级别">
          <el-option
              v-for="opt in registleOptions"
              :key="opt.id"
              :label="opt.name"
              :value="opt.id"
          />
        </el-select>
      </el-form-item>

      <!-- 剩余名额 -->
      <el-form-item label="剩余名额">
        <el-input :value="quota" disabled suffix="个" />
      </el-form-item>

      <!-- 挂号科室 -->
      <el-form-item label="挂号科室" prop="deptid">
        <el-select v-model="form.deptid" placeholder="请选择科室">
          <el-option
              v-for="opt in deptOptions"
              :key="opt.id"
              :label="opt.name"
              :value="opt.id"
          />
        </el-select>
      </el-form-item>

      <!-- 午别 -->
      <el-form-item label="午别" prop="noon">
        <el-select v-model="form.noon" placeholder="请选择上午/下午">
          <el-option label="上午" value="上午" />
          <el-option label="下午" value="下午" />
        </el-select>
      </el-form-item>

      <!-- 看诊医生 -->
      <el-form-item label="看诊医生" prop="userid">
        <el-select v-model="form.userid" placeholder="请选择医生">
          <el-option
              v-for="opt in doctorOptions"
              :key="opt.id"
              :label="opt.name"
              :value="opt.id"
          />
        </el-select>
      </el-form-item>

      <!-- 结算类别 -->
      <el-form-item label="结算类别" prop="settleid">
        <el-select v-model="form.settleid" placeholder="请选择结算类别">
          <el-option
              v-for="opt in settleOptions"
              :key="opt.id"
              :label="opt.name"
              :value="opt.id"
          />
        </el-select>
      </el-form-item>

      <!-- 收费方式 -->
      <el-form-item label="收费方式" prop="feetype">
        <el-select v-model="form.feetype" placeholder="请选择收费方式">
          <el-option
              v-for="opt in feeOptions"
              :key="opt.id"
              :label="opt.name"
              :value="opt.id"
          />
        </el-select>
      </el-form-item>

      <!-- 病历本 -->
      <el-form-item label="病历本">
        <el-switch v-model="form.isbook" active-value="Y" inactive-value="N" />
      </el-form-item>

      <!-- 应收金额 -->
      <el-form-item label="应收金额（元）">
        <el-input v-model="form.amount" disabled />
      </el-form-item>

      <!-- 提交 / 重置 -->
      <el-form-item>
        <el-button type="primary" @click="onSubmit">挂号</el-button>
        <el-button @click="onReset">清空</el-button>
      </el-form-item>
    </el-form>

    <!-- 缴费 & 打印发票 -->
    <div v-if="lastRegistId" class="mt-4">
      <el-button type="success" @click="onPay">缴费</el-button>
      <el-button type="primary" @click="onPrint">打印发票</el-button>
    </div>
  </el-card>
</template>

<script setup>
import { reactive, ref, onMounted, watch } from 'vue'
import axios from 'axios'
import { ElMessage } from 'element-plus'
import { useCounterStore } from '@/stores/counter'

const counterStore = useCounterStore()

// 表单模型
const form = reactive({
  casenumber: '',
  realname: '',
  gender: null,
  idnumber: '',
  birthdate: null,
  age: '',
  agetype: '',
  homeaddress: '',
  registleid: null,
  deptid: null,
  noon: '',
  userid: null,
  settleid: null,
  feetype: null,
  isbook: 'N',
  amount: null
})

// 校验规则
const rules = {
  realname:   [{ required: true, message: '请输入姓名', trigger: 'blur' }],
  gender:     [{ required: true, message: '请选择性别', trigger: 'change' }],
  idnumber:   [{ required: true, message: '请输入身份证号', trigger: 'blur' }],
  agetype:    [{ required: true, message: '请选择年龄类型', trigger: 'change' }],
  registleid: [{ required: true, message: '请选择挂号级别', trigger: 'change' }],
  deptid:     [{ required: true, message: '请选择科室', trigger: 'change' }],
  noon:       [{ required: true, message: '请选择午别', trigger: 'change' }],
  userid:     [{ required: true, message: '请选择医生', trigger: 'change' }],
  settleid:   [{ required: true, message: '请选择结算类别', trigger: 'change' }],
  feetype:    [{ required: true, message: '请选择收费方式', trigger: 'change' }]
}
const registerForm = ref(null)

// 下拉数据 & 状态
const registleOptions = ref([])
const deptOptions     = ref([])
const allDoctors      = ref([])
const doctorOptions   = ref([])
const settleOptions   = ref([])
const feeOptions      = ref([])
const quota           = ref(null)

// 最近挂号记录
const lastRegistId   = ref(null)
const lastCasenumber = ref('')
const lastAmount     = ref(null)

// 通用：提取 records / data
function toArr(r) {
  if (Array.isArray(r)) return r
  if (r?.records) return r.records
  if (r?.data)    return r.data
  return []
}

// 初始化下拉
async function loadOptions() {
  const [rl, dp, st, us, ft] = await Promise.all([
    axios.get('/api/master/reglevel', { params:{ page:1, pageSize:999 } }),
    axios.get('/api/master/dept',     { params:{ page:1, pageSize:999 } }),
    axios.get('/api/master/settle/list'),
    axios.get('/api/master/user/list'),
    axios.get('/api/master/register/feeTypes')
  ])

  registleOptions.value = toArr(rl.data).map(l => ({ id:l.id, name:l.registname }))
  deptOptions.value     = toArr(dp.data).map(d => ({ id:d.id, name:d.deptname }))
  settleOptions.value   = toArr(st.data).map(s => ({ id:s.id, name:s.settlename }))

  // 关键：正确映射 Constantitem → {id,name}
  feeOptions.value = toArr(ft.data).map(i => ({
    id:   i.id,            // 注意这里用小写的 i.id
    name: i.constantname   // 注意这里用小写的 i.constantName
  }))

  allDoctors.value = toArr(us.data)
      .filter(u => Number(u.useType) === 3)
      .map(u => ({
        id:         u.id,
        name:       u.realName,
        deptID:     Number(u.deptID),
        registLeID: Number(u.registLeID)
      }))
  doctorOptions.value = []
}

// 筛选医生
function updateDoctorOptions() {
  if (!form.deptid || !form.registleid) {
    doctorOptions.value = []
    return
  }
  doctorOptions.value = allDoctors.value.filter(
      d => d.deptID === Number(form.deptid) && d.registLeID === Number(form.registleid)
  )
}

// 获取限额 & 金额
async function fetchQuota() {
  if (!form.registleid) return quota.value = null
  try {
    const r = await axios.get('/api/master/register/getQuota', {
      params:{ registleid:form.registleid, noon:form.noon }
    })
    quota.value = r.data.quota
  } catch {
    ElMessage.error('获取限额失败')
  }
}
async function fetchAmount() {
  if (!form.registleid) return form.amount = null
  try {
    const r = await axios.get('/api/master/register/calcAmount', {
      params:{ registleid:form.registleid, isbook:form.isbook }
    })
    form.amount = r.data.amount
  } catch {
    ElMessage.error('计算应收金额失败')
  }
}

// 出生日期 → 年龄 & 类型
watch(() => form.birthdate, bd => {
  if (!bd) {
    form.age = ''
    form.agetype = ''
    return
  }
  const birth = new Date(bd)
  const now   = new Date()
  const days  = Math.floor((now - birth)/86400000)
  if (days < 30) {
    form.age = days; form.agetype = '天'
  } else {
    const months = Math.floor(days/30)
    if (months < 24) {
      form.age = months; form.agetype = '月'
    } else {
      form.age = Math.floor(months/12); form.agetype = '岁'
    }
  }
})

// 监听科室/级别/午别/病历本
watch(
    [() => form.deptid, () => form.registleid, () => form.noon],
    async () => {
      form.userid = null
      updateDoctorOptions()
      await Promise.all([fetchQuota(), fetchAmount()])
    }
)
watch(() => form.isbook, fetchAmount)

// 提交挂号
async function onSubmit() {
  await registerForm.value.validate()
  try {
    const { data } = await axios.post(
        '/api/master/register',
        form,
        { headers:{ 'X-User-Id': counterStore.userId } }
    )
    lastRegistId.value   = data.id
    lastCasenumber.value = data.casenumber
    lastAmount.value     = form.amount
    form.casenumber      = data.casenumber
    ElMessage.success('挂号成功，病历号：' + data.casenumber)
    onReset()
  } catch {
    ElMessage.error('挂号失败')
  }
}

// 缴费
async function onPay() {
  if (!lastRegistId.value) return ElMessage.error('请先挂号')
  try {
    await axios.post(
        '/api/master/register/pay',
        { registId: lastRegistId.value, amount: lastAmount.value },
        { headers:{ 'X-User-Id': counterStore.userId } }
    )
    ElMessage.success('缴费成功')
  } catch (e) {
    ElMessage.error('缴费失败：' + (e.response?.data?.error||''))
  }
}

// 打印发票
async function onPrint() {
  if (!lastRegistId.value) return ElMessage.error('请先缴费')
  try {
    const { data: inv } = await axios.get('/api/master/register/receipt', {
      params:{ registId: lastRegistId.value }
    })
    // …保持不变…
  } catch (e) {
    ElMessage.error('打印失败：' + (e.response?.data?.error||''))
  }
}

// 重置
function onReset() {
  Object.assign(form, {
    casenumber:'', realname:'', gender:null, idnumber:'',
    birthdate:null, age:'', agetype:'',
    homeaddress:'', registleid:null, deptid:null,
    noon:'', userid:null, settleid:null, feetype:null,
    isbook:'N', amount:null
  })
  quota.value = null
  doctorOptions.value = []
}

onMounted(loadOptions)
</script>

<style scoped>
.flex-between {
  display: flex;
  justify-content: space-between;
  align-items: center;
}
.mt-4 {
  margin-top: 16px;
}
</style>
